﻿
using System;
using System.Linq;
using SuperSimpleWebshop.Common;
using SuperSimpleWebshop.Domain;
using SuperSimpleWebshop.Domain.Helpers;
using SuperSimpleWebshop.Domain.Interfaces;
using SuperSimpleWebshop.Domain.Repositories;
using umbraco;
using umbraco.BusinessLogic;
using umbraco.presentation.nodeFactory;
using System.Threading;
using umbraco.cms.businesslogic.web;

public partial class SagePay_Handler : System.Web.UI.UserControl
{
    IOrderRepository _OrderRepository = new OrderRepository();

    protected void Page_Load(object sender, EventArgs e)
    {
        // PayPal POSTS some values
        string paymentStatus = library.Request("Status");

        // Get identifier created with the RequestHandler
        string transactionId = library.Request("VendorTxCode");

        // Match  identifier to order
        var order = this._OrderRepository.GetOrderByPaymentTransactionId(transactionId);

        // Check for match
        if (order != null)
        {
            // Get statusses from payment provider Response
            switch (paymentStatus)
            {
                case "OK":
                    order.OrderInfo.Status = OrderStatus.Ready_for_Dispatch;
                    order.Save();

                    CreateAcknowlegeReceipt(order, "OK", "");
                    break;
                case "MALFORMED":
                    order.OrderInfo.Status = OrderStatus.Payment_Failed;
                    order.OrderInfo.PaymentInfo.PaymentErrorMessage = library.Request("StatusDetail");
                    order.Save();

                    CreateAcknowlegeReceipt(order, "INVALID", "Malformed");
                    break;
                case "INVALID":
                    order.OrderInfo.Status = OrderStatus.Payment_Failed;
                    order.OrderInfo.PaymentInfo.PaymentErrorMessage = library.Request("StatusDetail");
                    order.Save();

                    CreateAcknowlegeReceipt(order, "INVALID", "");
                    break;
                case "ERROR":
                    order.OrderInfo.Status = OrderStatus.Payment_Failed;
                    order.OrderInfo.PaymentInfo.PaymentErrorMessage = library.Request("StatusDetail");
                    order.Save();

                    CreateAcknowlegeReceipt(order, "ERROR", "");
                    break;
            }
            order.Save();
        }
    }

    #region acknowledge receipt

    /*
     VPSProtocol=2.23&
     * TxType=PAYMENT&
     * VendorTxCode=20ec946d-f054-4233-ae2f-358f69098142&
     * VPSTxId={06C40C63-9161-4D30-9B93-A22D2495B868}&
     * Status=OK&
     * TxAuthNo=6775&
     * AVSCV2=ALL+MATCH&
     * AddressResult=MATCHED&
     * PostCodeResult=MATCHED&
     * CV2Result=MATCHED&
     * GiftAid=0&
     * 3DSecureStatus=OK&
     * CAVV=MN9BY402TAFBVRCTWG5WAN&
     * CardType=VISA&
     * Last4Digits=4325&
     * VPSSignature=91D87CB01EC1C19161A56BCF39FFE6DA
     */
    public void CreateAcknowlegeReceipt(Order order, string status, string errorDetails)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        var baseUrl = string.Format("http://{0}", GetTopLevelDomain());
        var oldUICulture = Thread.CurrentThread.CurrentUICulture;
        var oldCulture = Thread.CurrentThread.CurrentCulture;
        var shopAliasNode = ShopAliasHelper.GetAllShopAlias().Where(x => x.Name.ToLower() == order.OrderInfo.ShopAlias.Alias.ToLower()).FirstOrDefault();

        Thread.CurrentThread.CurrentCulture = shopAliasNode.CultureInfo;
        Thread.CurrentThread.CurrentUICulture = shopAliasNode.CultureInfo;

        var nodeId = DomainHelper.GetNodeIdForDocument("sswsOrderProcessNode", library.GetDictionaryItem("PaymentConfirmation"), order.OrderInfo.Alias);
        //var cancelNodeId = DomainHelper.GetNodeIdForDocument("sswsOrderProcessNode", library.GetDictionaryItem("PaymentConfirmationFailed"), order.OrderInfo.Alias);

        Thread.CurrentThread.CurrentUICulture = oldUICulture;
        Thread.CurrentThread.CurrentCulture = oldCulture;

        var returnUrl = string.Format("{0}{1}", baseUrl.Substring(0, baseUrl.LastIndexOf("/")), library.NiceUrl(nodeId));
        
        sb.Append("Status=OK\r\n");
		sb.Append("RedirectURL=" + returnUrl + "\r\n");
		sb.Append("StatusDetail=\r\n");

        // now set our literal to return to sagepay
        Response.Write(sb.ToString());
    }

    public string GetTopLevelDomain() // too much code but works for now
    {
        try
        {
            Node parent = new Node(-1);
            foreach (Node child in parent.Children)
            {
                Domain[] domains = library.GetCurrentDomains(child.Id);
                if (domains != null && domains.Length >= 0)
                {
                    foreach (Domain d in domains)
                    {
                        return d.Name.ToString();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message.ToString());
        }
        return "";
    }

    #endregion
}